<template>
  <div class="user-sidebar" v-if="isLoggedIn">
    <!-- 用户信息区域 -->
    <div class="user-profile-card">
      <div class="user-avatar-section">
        <div class="user-basic-info">
          <h3 class="username">{{ userInfo.nickname || userInfo.phone }}</h3>
          <p class="user-status" v-if="userStore.getPremiumStatus">
            <span class="premium-icon">👑</span>
            <span>{{ t('premium_member') || '高级会员' }}</span>
          </p>
          <p class="user-phone" v-if="userInfo.phone">{{ userInfo.phone }}</p>
        </div>
      </div>
      
      <!-- 快捷操作 -->
      <div class="quick-actions">
        <!-- 用户头像 -->
        <div class="user-avatar-container"  v-if="userInfo.avatar" >
          <div class="user-avatar-img">
            <img :src="userInfo.avatar" alt="用户头像" @error="handleAvatarError" />
          </div>
        </div>
        
        <button class="action-btn" @click="goToUserCenter">
          <i class="icon">👤</i>
          {{ t('personal_info') || '个人信息' }}
        </button>
        <button class="action-btn" @click="goToRecharge">
          <i class="icon">💳</i>
          {{ t('recharge') || '充值' }}
        </button>
        <button class="action-btn logout-btn" @click="handleLogout">
          <i class="icon">🚪</i>
          {{ t('logout') || '退出登录' }}
        </button>
      </div>
    </div>

    <!-- 访问历史区域 -->
    <div class="history-card">
      <div class="card-header">
        <h4>{{ t('recent_consultations') || '最近咨询' }}</h4>
        <button class="view-all-btn" @click="goToUserCenter">{{ t('view_all') || '查看全部' }}</button>
      </div>
      
      <div class="history-list">
        <div 
          v-for="(item, index) in recentHistory" 
          :key="index" 
          class="history-item"
          @click="viewHistoryDetail(item)"
        >
          <div class="history-icon">
            <i class="icon">📋</i>
          </div>
          <div class="history-content">
            <div class="history-title" :class="{'text-red': item.esey === 1, 'text-blue': item.esey !== 1}">
              {{ t('consultation_number') || '咨询编号' }}: {{ item.id }}
            </div>
            <div class="history-desc">{{ t(item.msg_title) }}</div>
            <div class="history-time">{{ formatTime(item.create_time) }}</div>
          </div>
        </div>
        
        <div class="empty-history" v-if="recentHistory.length === 0">
          <p>{{ t('no_recent_consultations') || '暂无最近咨询记录' }}</p>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-card">
      <div class="card-header">
        <h4>{{ t('usage_statistics') || '使用统计' }}</h4>
      </div>
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-number">{{ userStats.totalConsultations || 0 }}</div>
          <div class="stat-label">{{ t('total_consultations') || '总咨询次数' }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ userStats.freeQueries || 0 }}</div>
          <div class="stat-label">{{ t('remaining_free_queries') || '剩余免费次数' }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/userStore'
import { useLanguageStore } from '@/store/languageStore'
import request from '@/utils/request'
// import defaultAvatar from '@/assets/images/default-avatar.png'

const router = useRouter()
const userStore = useUserStore()
const languageStore = useLanguageStore()

// 响应式数据
const recentHistory = ref([])
const userStats = ref({
  totalConsultations: 0,
  freeQueries: 0
})
console.log(userStore.getUserInfo, '用户信息');

// 计算属性
const userInfo = computed(() => userStore.getUserInfo)
const isLoggedIn = computed(() => userStore.getIsLoggedIn)

const t = (key) => languageStore.t(key)

// 获取最近的咨询历史
const fetchRecentHistory = async () => {
  try {
    const res = await request({
      url: '/v6/user/history',
      method: 'post',
      data: {
        page: 1,
        title: ''
      }
    })
    
    if (res.code === 0 && res.data) {
      // 只取前5条记录用于侧栏显示
      const historyData = res.data.data || []
      recentHistory.value = historyData.slice(0, 5)
      userStats.value.totalConsultations = res.data.total || historyData.length
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    // 如果API调用失败，使用空数据
    recentHistory.value = []
    userStats.value.totalConsultations = 0
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp * 1000)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
  if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
  return Math.floor(diff / 86400000) + '天前'
}

// 跳转到用户中心
const goToUserCenter = () => {
  router.push('/user-center')
}

// 跳转到充值页面
const goToRecharge = () => {
  router.push('/chat/recharge')
}

// 处理退出登录
const handleLogout = () => {
  userStore.logout()
  router.push({
    name: 'home'
  })
}

// 处理头像加载失败
const handleAvatarError = (event) => {
  // 头像加载失败时隐藏img标签，显示文字头像
  event.target.style.display = 'none'
}

// 查看历史详情
const viewHistoryDetail = (item) => {
  // 跳转到历史详情页面
  router.push({
    path: '/history-detail',
    query: {
      history_id: item.history_id,
      answer_id: item.answer_id,
      person_menu_id: item.person_menu_id,
      person_menu_item_id: item.person_menu_item_id,
      is_show_time_res: item.is_show_time_res
    }
  });
};

// 组件挂载时获取数据
onMounted(() => {
  if (isLoggedIn.value) {
    fetchRecentHistory()
  }
})

// 监听登录状态变化，当用户登录时重新获取数据
watch(isLoggedIn, (newValue) => {
  if (newValue) {
    fetchRecentHistory()
  } else {
    // 用户退出登录时清空数据
    recentHistory.value = []
    userStats.value = {
      totalConsultations: 0,
      freeQueries: 0
    }
  }
})
</script>

<style scoped lang="less">
.user-sidebar {
  width: 280px;
  height: calc(100vh - 60px);
  background-color: #ffffff;
  border-right: 1px solid #e5e7eb;
  overflow-y: auto;
  position: fixed;
  left: 0;
  top: 60px;
  z-index: 10;
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.08);
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: #f9fafb;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #d1d5db;
    border-radius: 3px;
    
    &:hover {
      background: #9ca3af;
    }
  }
}

.user-profile-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  margin: 16px;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.user-avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-avatar-container {
  width: 48px;
  height: 48px;
  margin-right: 12px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #1989fa 0%, #40a9ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.3);
}

.user-avatar-img {
  width: 100%;
  height: 100%;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
  }
}

.user-avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.user-basic-info {
  flex: 1;
}

.user-name {
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 4px;
}

.user-status {
  color: #1989fa;
  font-size: 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  
  .premium-icon {
    margin-right: 4px;
  }
}

.user-phone {
  color: #6b7280;
  font-size: 12px;
  margin-bottom: 8px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.02);
  
  .icon {
    margin-right: 10px;
    font-size: 16px;
    color: #6b7280;
  }
  
  &:hover {
    background: linear-gradient(135deg, #1989fa 0%, #40a9ff 100%);
    border-color: #1989fa;
    color: #ffffff;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(25, 137, 250, 0.15);
    
    .icon {
      color: #ffffff;
    }
  }
  
  &.logout-btn:hover {
    background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
    border-color: #ef4444;
    color: #ffffff;
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.15);
    
    .icon {
      color: #ffffff;
    }
  }
}

.history-card, .stats-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  margin: 16px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
  border-bottom: 1px solid rgba(229, 231, 235, 0.8);
  background: linear-gradient(135deg, rgba(248, 250, 252, 0.8) 0%, rgba(255, 255, 255, 0.4) 100%);
  border-radius: 12px 12px 0 0;
  
  h4 {
    color: #1f2937;
    font-size: 15px;
    font-weight: 600;
    margin: 0;
  }
}

.view-all-btn {
  color: #1989fa;
  font-size: 12px;
  background: linear-gradient(135deg, rgba(25, 137, 250, 0.08) 0%, rgba(64, 169, 255, 0.04) 100%);
  border: 1px solid rgba(25, 137, 250, 0.2);
  border-radius: 6px;
  padding: 6px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  
  &:hover {
    color: #ffffff;
    background: linear-gradient(135deg, #1989fa 0%, #40a9ff 100%);
    border-color: #1989fa;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(25, 137, 250, 0.2);
  }
}

.history-list {
  padding: 0 20px 16px;
}

.history-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  margin: 4px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  
  &:hover {
    background: linear-gradient(135deg, rgba(25, 137, 250, 0.06) 0%, rgba(64, 169, 255, 0.03) 100%);
    border-color: rgba(25, 137, 250, 0.15);
    transform: translateX(4px);
  }
}

.history-icon {
  margin-right: 12px;
  
  .icon {
    font-size: 16px;
    color: #1989fa;
  }
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-title {
  color: #1f2937;
  font-size: 13px;
  font-weight: 500;
  margin-bottom: 4px;
  line-height: 1.4;
}

.history-desc {
  color: #e0e0e0;
  font-size: 12px;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-time {
  color: #9ca3af;
  font-size: 11px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #9ca3af;
  font-size: 13px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 20px;
}

.stat-item {
  text-align: center;
  padding: 12px 8px;
  background: linear-gradient(135deg, rgba(25, 137, 250, 0.06) 0%, rgba(64, 169, 255, 0.03) 100%);
  border-radius: 10px;
  border: 1px solid rgba(25, 137, 250, 0.15);
  transition: all 0.3s ease;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(25, 137, 250, 0.1);
    background: linear-gradient(135deg, rgba(25, 137, 250, 0.1) 0%, rgba(64, 169, 255, 0.06) 100%);
  }
}

.stat-number {
  color: #1989fa;
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 6px;
}

.stat-label {
  color: #6b7280;
  font-size: 11px;
  font-weight: 500;
  line-height: 1.3;
  word-wrap: break-word;
  hyphens: auto;
  overflow-wrap: break-word;
  max-width: 100%;
}

// 移动端隐藏侧边栏
@media (max-width: 768px) {
  .user-sidebar {
    display: none;
  }
}
</style>
